// import  _fetch  from "./_fetch.js";
const menu = document.querySelector(".headerLeft");
const menuIcon = document.querySelector(".headerLeft i");

const search = document.querySelector(".headerRight");
const searchIcon = document.querySelector(".headerRight i");


const mask1 = document.querySelector(".mask1");
const mask2 = document.querySelector(".mask2");

const box1 = document.querySelector('.mask1 .box');

// 页面底部节点 事件委托
const footer = document.querySelector("footer");


// pc端普通屏页面底部高度
let footerHeight = 5;

// // 网页可见区域宽 用来协助响应式
let offsetWidth = document.body.offsetWidth;

// token值(用于后台官网的身份识别)
let token;

// // 视频播放
// // 播放按钮
const playIcon= document.querySelector('.videoMask i');
const videoMask= document.querySelector('.videoMask');
const videoMain = document.querySelector('.videoBox .videoContent .videoMain');

// 轮播图左右箭头 通过getElementsByClassName()动态获取
const leftArrow=document.getElementsByClassName('swiper-button-prev');
const rightArrow=document.getElementsByClassName('swiper-button-next');
// 顶部轮播图
let swipeTopArr;
const swipeTopBox=document.querySelector('.swiper');
const swipeTopNode=document.querySelector('.swiper-wrapper');
// 预加载轮播图
let swipeIndex=0;

// 专门用来缓存图片的节点
let preloadImgNode = document.createElement("img");

window.addEventListener('load',async ()=>{
	if(sessionStorage.getItem("tokenKey")&&sessionStorage.getItem("indexSwipeTopArrKey")){
		// 从sessionStorage中获取token
		token=JSON.parse(sessionStorage.getItem("tokenKey"));
		swipeTopArr=JSON.parse(sessionStorage.getItem('indexSwipeTopArrKey'));
		
		// console.log(swipeTopArr);
	}else{
		token = (await _fetch('POST','http://website.bluej.cn/api/admin/login',
				{
		          phone: '18771955164',
		          password: '123456',
		        }
		      )).data.token;
			  
		swipeTopArr=(await _fetch('GET','http://website.bluej.cn/api/carouselGroup/getAllCarouselGroup')).data.rows[0].Carousels;
		console.log(swipeTopArr);
		
		// 将token值保存到sessionStorage中
		sessionStorage.setItem("tokenKey", JSON.stringify(token));
		// console.log(token);
		sessionStorage.setItem('indexSwipeTopArrKey',JSON.stringify(swipeTopArr));
	}
	
	while(true){
		if(swipeIndex==swipeTopArr.length){
			break;
		}
		await preloadImg();
	}
	// console.log(swipeTopArr);
	// // 渲染轮播图
	let swipeTopStr='';
	swipeTopArr.forEach((item,index)=>{
		swipeTopStr+=`
		<div class="swiper-slide">
			<img src='${swipeTopArr[index].url}'>
		</div>
		`;
	});
	
	

	// console.log(`<div class="swiper-wrapper">${swipeTopStr}</div>`+`<div class="swiper-pagination"></div>`);
	
	swipeTopBox.innerHTML=`<div class="swiper-wrapper">${swipeTopStr}</div>`+`<div class="swiper-pagination"></div>`+`<div class="swiper-button-prev"></div>
						<div class="swiper-button-next"></div>`;
	
	// 轮播图
	let mySwiper = new Swiper('.swiper', {
		autoplay: true, //可选选项，自动滑动
		loop: true,
		slideToClickedSlide: true,
		mousewheel: true,
		pagination: { //分页器代码 具体看官网
			el: '.swiper-pagination',
			clickable: true,
		},
		navigation: {
		      nextEl: '.swiper-button-next',
		      prevEl: '.swiper-button-prev',
		},
	})
	
	// 设置视频路径
	videoMain.src = 'https://www.runoob.com/try/demo_source/movie.mp4';
});


// 图片的缓存
function preloadImg(){
	return new Promise((resolve,reject)=>{
		preloadImgNode.addEventListener('load',()=>{
			resolve();
		},{once:true});
		
		preloadImgNode.src=swipeTopArr[swipeIndex].url;
		swipeIndex++;
	});
}

menu.addEventListener("click", function() {
	if (menuIcon.classList.contains('icon-caidan')) {
		mask1.style.clipPath = "circle(95%)";
		
		menuIcon.style.color = "#d576ba";
		menu.style.background = "#fff";
		menuIcon.classList.remove('icon-caidan');
		menuIcon.classList.add('icon-closel');
		search.style.transform = 'scale(0)';
		mask2.style.transform = 'scale(0)';
	
	} else {
		// mask1.style.clipPath = `circle(${radius}vw at ${positionX}% ${positionY}vw)`;
		mask1.style.clipPath = ``;
		menuIcon.style.color = "#fff";
		menu.style.background = "";
		menuIcon.classList.remove('icon-closel');
		menuIcon.classList.add('icon-caidan');
		search.style.transform = 'scale(1)';
		mask2.style.transform = 'scale(1)';
	}

});

search.addEventListener("click", function() {	
	if (searchIcon.classList.contains('icon-sousuo')) {
		mask2.style.clipPath = "circle(75%)";
		searchIcon.style.color = "#d576ba";
		search.style.background = "#fff";
		searchIcon.classList.remove('icon-sousuo');
		searchIcon.classList.add('icon-closel');
		menu.style.transform = 'scale(0)';
		mask1.style.transform = 'scale(0)';
	} else {
		mask2.style.clipPath = "";
		searchIcon.style.color = "#fff";
		search.style.background = "";
		searchIcon.classList.remove('icon-closel');
		searchIcon.classList.add('icon-sousuo');
		menu.style.transform = 'scale(1)';
		mask1.style.transform = 'scale(1)';
	}
});



footer.addEventListener("click", function(event) {
	// 网页可见区域宽 用来协助响应式
	// let offsetWidth = document.body.offsetWidth;
	if (offsetWidth <= 767) {
		footerHeight = 11;
	} else if (offsetWidth <= 2339 && offsetWidth >= 1025) {
		footerHeight = 5;
	}

	footerF(event.target.id);
});





// 点击视频播放
playIcon.addEventListener('click',()=>{
	videoMask.style.display='none';
	videoMain.setAttribute('controls','controls');
	videoMain.play();	
});
// 点击视频重播
videoMain.addEventListener('ended',()=>{
	videoMask.style.display='block';
	videoMain.removeAttribute('controls');
	document.querySelector('.videoMask i').classList.remove('icon-bofang');
	document.querySelector('.videoMask i').classList.add('icon-zhongbo-m');
});

// 鼠标移入移出箭头出现消失
swipeTopBox.addEventListener('mouseenter',()=>{
	leftArrow[0].style.visibility='visible';
	rightArrow[0].style.visibility='visible';
});
swipeTopBox.addEventListener('mouseleave',()=>{
	leftArrow[0].style.visibility='hidden';
	rightArrow[0].style.visibility='hidden';
});

// 渲染底部
function footerF(ID) {

	let footerStr = '';
	switch (ID) {
		case 'up':
			footer.style.height = `${footerHeight*2.4}vw`;
			// console.log(footer.style.height)
			footer.style.marginTop = `${-footerHeight*2.4}vw`;
			footer.style.transition = 'all .3s';
			footerStr += `
				<div class="content1">
					<div class="left">
						<h2>Receive the latest Or news and Creativity in our newsletters.</h2>
						<form action="" method="">
							<input type="email" name="" id="login" value="" placeholder='enter address'/>
							<label for="login">Sign Up</label>
						</form>
					</div>
					<div class="right">
						<i class="iconfont icon-xinlangweibo"></i>
						<i class="iconfont icon-weixin"></i>
						<i class="iconfont icon-baidu"></i>
						<i class="iconfont icon-facebookfacebook52"></i>
						<i class="iconfont icon-xiajiantou" id="down"></i>
					</div>
				</div>
				<p>Copyright (c) Nissin Furniture Crafters Co ,Ltd All Rights Reserved</p>
			`;
			footer.innerHTML = footerStr;
			break;

		case 'down':
			footer.style.height = `${footerHeight}vw`;
			footer.style.marginTop = `${-footerHeight}vw`;
			footer.style.transition = 'all .3s';
			footerStr += `
				<div class="content">
					<h2>Copyright (c) Nissin Furniture Crafters Co ,Ltd All Rights Reserved</h2>
					<i class="iconfont icon-shangjiantou" id="up"></i>
				</div>
			`;
			footer.innerHTML = footerStr;
			break;
	}

}

// 从后台获取数据的方法
async function _fetch(_method, _url, _data) {
  let paramsObj = {
    method: _method,
  };
  // 若使用的方法是get
  if (_method === "GET") {
    paramsObj["headers"] = { "x-token": `${token}` };
    if (_data) {
      _url += "?";
      for (const key in _data) {
        _url += `${key}=${_data[key]}&`;
      }
      _url = _url.slice(0, -1);
    }
  } else {
    paramsObj["headers"] = {
      "Content-type": 'application/json',
    };
    let body = "";
    paramsObj["body"] =JSON.stringify(_data) ;
  }
  
  // console.log(paramsObj);

  let res = await fetch(_url, paramsObj);

  return res.json();
}